package com.yisu.es.executor;

import com.yisu.es.model.EsQueries;
import com.yisu.es.model.EsQuery;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.Map;

/**
 * @author xuyisu
 * @classname EsQueryExecutor
 * @description 执行查询
 */
@Slf4j
public class EsQueryExecutor {
    private final EsQueries esQueries;

    public EsQueryExecutor(EsQueries esQueries) {
        this.esQueries = esQueries;
    }

    /**
     * 执行查询请求
     *
     * @param queryId 查询的唯一标识符
     * @param params  查询参数
     * @param indices 索引名称
     * @return 查询结果
     * @throws IOException 如果发生IO异常
     * @throws IllegalArgumentException 如果未找到指定的查询
     */
    public String executeQuery(String queryId, Map<String, String> params,String... indices) throws IOException {
        EsQuery esQuery = esQueries.getQueries().stream()
                .filter(q -> q.getId().equals(queryId))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Query not found"));
        String queryString = replacePlaceholders(esQuery.getQuery(), params);
        log.info("Executing query with ID: {}, Query: {}, Params: {}", queryId, esQuery.getQuery(), params);

        return queryString;
    }


    /**
     * 替换模板中的占位符为实际值
     *
     * @param template 模板字符串，其中可能包含形如 "${key}" 的占位符
     * @param params   一个包含替换值的键值对集合
     * @return 替换占位符后的新字符串
     */
    private String replacePlaceholders(String template, Map<String, String> params) {
        return params.entrySet().stream()
                .reduce(template, (acc, entry) -> acc.replace("${" + entry.getKey() + "}", entry.getValue()),
                        (left, right) -> left);
    }


}

